package com.e3.web.widget.client;

import com.e3.web.core.client.GXTHelper;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;

public class MyDialog extends Window {
	
	private MyWidgetMessages MESSAGES = MyWidgetMessages.INSTANCE;
	
	public final static int OK = 1;
	public final static int CANCEL = 2;
	public final static int CLOSE = 3;
	public final static int OK_CANCEL = 4;
	public final static int OK_CLOSE = 5;
	
	private final String OK_NAME = MESSAGES.action_ok();
	public final String CANCEL_NAME = MESSAGES.action_cancel();
	public final String CLOSE_NAME = MESSAGES.action_close();
	
	private SelectionListener<ButtonEvent> btnSelectionListener = new SelectionListener<ButtonEvent>() {
	    @Override
	    public void componentSelected(ButtonEvent ce) {
	      onButtonPressed(ce.getButton());
	    }
	};
	
	private Button okButton;
	private Button cancelButton;
	private Button closeButton;
	
	public MyDialog() {
		this.setModal(true);

		this.setMaximizable(false);
		this.setMinimizable(false);

		initButtons();
	}

	private void initButtons() {
		Button[] btns = getButtons();
		for (int i=0;i<btns.length;i++) {
			Button btn = btns[i];
			if(btn != null){
				addButton(btn);
			}
		}
	}
	
	protected Button[] getButtons(){
		return new Button[]{getButton(OK),getButton(CANCEL)};
	}
	
	public Button getButton(int button){
		switch(button){
		case OK : if(okButton == null) okButton = createButton(OK_NAME); return okButton;
		case CANCEL: if(cancelButton == null) cancelButton = createButton(CANCEL_NAME); return cancelButton;
		case CLOSE: if(closeButton == null) closeButton = createButton(CLOSE_NAME); return closeButton;
		default:return null;
		}
		               
	}
	
	protected Button createButton(String name){
		Button button = new Button(name);
		button.addSelectionListener(btnSelectionListener);
		return button;
	}
	
	protected void onButtonPressed(Button button){
		if(button == okButton){
			onOk();
		}
		else if(button == cancelButton){
			onCancel();
		}
		else if(button == closeButton){
			onClose();
		}
	}

	protected void onClose() {
		GXTHelper.unmask(this);
		this.setVisible(false);
	}

	protected void onCancel() {
		GXTHelper.unmask(this);
		this.setVisible(false);
	}

	protected void onOk() {
		
	}
	
	public void setOKText(String text){
		okButton.setText(text);
	}
	
	public void setCancelText(String text){
		cancelButton.setText(text);
	}
	
	public void setCloseText(String text){
		closeButton.setText(text);
	}
	
}
